PortalJSON = {}

function PortalJSON.Encode(value)
  local function escape_str(s)
    s = tostring(s)
    s = s:gsub("\\", "\\\\")
    s = s:gsub("\"", "\\\"")
    s = s:gsub("\n", "\\n")
    s = s:gsub("\r", "\\r")
    s = s:gsub("\t", "\\t")
    return s
  end

  local function is_array(t)
    local count = 0
    for k, v in pairs(t) do
      if type(k) ~= "number" then
        return false
      end
      count = count + 1
    end
    return count == #t
  end

  local function encode_value(v)
    local t = type(v)
    if t == "string" then
      return "\"" .. escape_str(v) .. "\""
    elseif t == "number" or t == "boolean" then
      return tostring(v)
    elseif t == "table" then
      return PortalJSON.Encode(v)
    else
      return "null"
    end
  end

  if type(value) == "table" then
    if is_array(value) then
      -- 处理数组
      local parts = {}
      for i, v in ipairs(value) do
        table.insert(parts, encode_value(v))
      end
      return "[" .. table.concat(parts, ", ") .. "]"
    else
      -- 处理对象
      local parts = {}
      for k, v in pairs(value) do
        if type(k) == "string" then
          table.insert(parts, "\"" .. escape_str(k) .. "\": " .. encode_value(v))
        elseif type(k) == "number" then
          table.insert(parts, "\"" .. tostring(k) .. "\": " .. encode_value(v))
        end
      end
      return "{" .. table.concat(parts, ", ") .. "}"
    end
  else
    return encode_value(value)
  end
end

_G["PortalJSON"] = PortalJSON